<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
</head>
<body>
<div>
    <div id ="content"></div>
</div>
<div>
    <input type = "text" id="input">
    <button type="button" onclick="say()"><span>发送消息</span></button>
</div>
</body>
<script>
    const serverUri = "http://127.0.0.1:10246";
    const sendEvent = "ServerReceive";
    const receiveEvent = "ClientReceive";

    let socket;

    connect(1001);

    function connect(uid) {
        socket = io.connect(serverUri,{
            'force new connection': true,
            'query': 'UID='+uid
        });

        socket.on('connect', function () {
            console.log("连接成功");
            //如果发送字符串send("hello Server"); *需要修改服务端接收类型
            send({
                name:"client",
                message:"hello Server"
            });
        });
        //监听返回消息
        socket.on(receiveEvent, function (data) {
            let html = document.createElement('p')
            html.innerHTML = `系统消息：<span>${data.message}</span>`
            document.getElementById('content').appendChild(html)
        });

        socket.on('disconnect', function () {
            console.log("连接断开");
        });
    }

    function send(data){
        socket.emit(sendEvent,data);
    }

    function say(){
        let t = document.getElementById('input').value;
        send({
            server: t
        });
    }


</script>
</html>